package com.wxtf.platform.plugins.role;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;

/**
 * <li>Title: UserService.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.plugins.user</li>
 * <li>Description: 用户管理-表T_USER</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Jul 5, 2012 10:08:48 AM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class RoleAction extends LogicBase implements CommonsCallProvider {
	private static Log log = LogFactory.getLog(RoleAction.class);

	public RoleAction(String jsonArray) {

	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getExtendData());
				return msg.toString();
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("saveMenuTree".equals(this.getMethodName())) {
				msg = this.saveMenuTree(this.getLogicData());
			} else if ("listUser".equals(this.getMethodName())) {
				msg = this.listUser(this.getLogicData());
				return msg.toString();
			} else if ("listUser4".equals(this.getMethodName())) {
				msg = this.listUser4(this.getLogicData());
				return msg.toString();
			}else if ("listUser4Role".equals(this.getMethodName())) {//显示角色下的所有用户
				msg = this.listUser4Role(this.getExtendData());
				return msg.toString();
			} else if ("saveUser".equals(this.getMethodName())) {
				msg = this.saveUser(this.getLogicData());
			} else if ("delUser".equals(this.getMethodName())) {
				msg = this.delUser(this.getLogicData());
			} else if ("listGroup".equals(this.getMethodName())) {
				msg = this.listGroup(this.getLogicData());
				return msg.toString();
			} else if ("saveGroup".equals(this.getMethodName())) {
				msg = this.saveGroup(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if(msg == null || "[null]".equals(msg)){
				msg = "\"\"";
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
			//log.info(this.getClass().getName() +":"+this.getMethodName() + " -> " + msg);
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}
	
	@Override
	public Object select(Object jsonArray) throws Exception {		
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String sc_uid = user.getUserId();
		sql = " from T_ROLE";
		if(!"0".equals(sc_uid)){
			sql += " where role_id not in('0')";
		}
		HttpServletRequest request = this.getRequest();
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		if(sortname!=null&&sortname!=null) {
			sql +=" order by "+sortname+" "+sortorder+"";
		} else {
			sql += " order by logic_code";
		}
		String countSql = "select count(role_id)" + sql;
		String querySql = "select role_id,rparent_id,caption,logic_code,action,action1,action2 " + sql;
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}

	private String[] fields = { "role_id", "rparent_id", "caption", "logic_code", "action", "action1", "action2" };
	@Override
	public Object insert(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		String loginSql = "select count(*) from t_role where caption='"+jsonObject.getString("caption")+"'";
		List<Object> ls = AccessDataBaseUtil.query4List(loginSql,new Object[]{});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if(hasId>0){
			return "\"角色名称不能重复\"";
		}
		obj[0] = AccessDataBaseUtil.getPKUUID();
		
		sql = "insert into t_role(role_id,rparent_id,caption,logic_code,action,action1,action2) values(?,?,?,?,?,?,?)";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		return "\"新建成功\"";
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		Object[] obj = new Object[fields.length];
		for (int j = 0; j < fields.length - 1; j++) {
			obj[j] = jsonObject.getString(fields[j+1]);
		}
		String caption = jsonObject.getString("caption");
		String caption1 = jsonObject.getString("caption1");
		if(!caption.equals(caption1)){
			String loginSql = "select count(*) from t_role where caption='"+caption+"'";
			List<Object> ls = AccessDataBaseUtil.query4List(loginSql,new Object[]{});
			int hasId = Integer.parseInt(ls.get(0).toString());
			if(hasId>0){
				return "\"角色名称不能重复\"";
			}
		}		
		obj[obj.length - 1] = jsonObject.getString(fields[0]);
		sql = "update t_role set rparent_id = ?,caption = ?,logic_code = ?,action = ?,action1 = ?,action2 = ? where role_id = ?";
		AccessDataBaseUtil.executeSQLUpdate(sql, obj);
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		String[] ids = id.split(",");
		String sql = "delete from T_ROLE where ROLE_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, ids);
		return "\"删除成功\"";
	}

	/** 
	 * 描述：saveMenuTree 保存所选的菜单
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:42 PM
	 * @author chun_chang
	 */
	public Object saveMenuTree(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("roleId");
		String id2 = jsonObject.getString("permissionId");
		String[] ids = id2.split(",");
		
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		buff.append("delete from T_ROLE_PERMISSION where ROLE_ID = '").append(id).append("'");
		list.add(buff.toString());
		
		if(!"".equals(id2)){
			buff.setLength(0);
			for (String id1 : ids) {
				buff.append("insert into T_ROLE_PERMISSION(R_P_ID,ROLE_ID,PERMISSION_ID)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(id).append("',")
				.append("'").append(id1).append("'")
				.append(")");
				list.add(buff.toString());
				buff.setLength(0);
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}

	/** 
	 * 描述：listUser 该角色下的用户列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:53 PM
	 * @author chun_chang
	 */
	public Object listUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String userName = jsonObject.getString("userName");
		
		sql = " from t_user r left join t_user_role s on r.user_id = s.user_id and s.role_id = ? ";
		if (StringUtils.isNotBlank(userName)) {
			sql += "where r.caption like '%" + userName + "%'";
		}
		String countSql = "select count(*)" + sql;
		String querySql = "select r.user_id, r.caption, s.role_id" + sql + " order by s.role_id desc";
		String[] fields = { "user_id", "caption", "role_id"};
		Object[] params = { roleId };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
	}
	/** 
	 * 描述：listUser 可选用户
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:12:53 PM
	 * @author chun_chang
	 */
	public Object listUser4(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String userName = jsonObject.getString("userName");
		String jigou = jsonObject.getString("jigou");
		
		sql =" from t_user aa where aa.user_id not in ( select u.user_id  from t_user u,t_user_role tu where u.user_id = tu.user_id and tu.role_id = ? )";	
		if (StringUtils.isNotBlank(jigou)) {
			sql = " from (select o.user_id, o.caption from t_user o where o.user_id not in ( select u.user_id  from t_user u,t_user_role tu where u.user_id = tu.user_id and tu.role_id = ? ) ) aa,( select distinct r.user_id from t_department s,t_user_department r where r.department_id = s.department_id and s.caption like '%" + jigou + "%') bb where aa.user_id = bb.user_id";
		}
		if (StringUtils.isNotBlank(userName)) {
			sql += " and aa.caption like '%" + userName + "%'";
		}
		
		String countSql = "select count(*)" + sql;
		String querySql = "select aa.user_id, aa.caption" + sql + " order by aa.caption asc";
		String[] fields = { "user_id", "caption"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ roleId });
	}
	
	/** 
	 * 描述：listUser4Role 已选用户
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Sep 17, 2012  3:41:49 PM
	 * @author chun_chang
	 */
	public Object listUser4Role(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String userName = jsonObject.getString("userName");
		String jigou = jsonObject.getString("jigou");
		
		sql =" from t_user_role p, t_user aa where p.USER_ID = aa.USER_ID and p.ROLE_ID = ?";	
		if (StringUtils.isNotBlank(jigou)) {
			sql = " from ( select q.user_id, q.caption from t_user_role p, t_user q where p.user_id = q.user_id and p.role_id = ?) aa,( select distinct r.user_id from t_department s,t_user_department r where r.department_id = s.department_id and s.caption like '%" + jigou + "%') bb where aa.user_id = bb.user_id";
		}
		if (StringUtils.isNotBlank(userName)) {
			sql += " and aa.caption like '%" + userName + "%'";
		}
		String countSql = "select count(*)" + sql;
		String querySql = "select aa.user_id, aa.caption" + sql + " order by aa.caption asc";
		String[] fields = { "user_id", "caption" };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), new Object[]{ roleId });
	}

	/** 
	 * 描述：saveUser 保存新的用户列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:13:07 PM
	 * @author chun_chang
	 */
	public Object saveUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		sql = "delete from T_USER_ROLE where ROLE_ID = '" + roleId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, userId);
		
		buff.setLength(0);
		for (String id1 : userId) {
			buff.append("insert into T_USER_ROLE(U_R_ID,ROLE_ID,USER_ID)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(roleId).append("',")
				.append("'").append(id1).append("'")
				.append(")");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	
	public Object delUser(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String userIds = jsonObject.getString("userId");
		String[] userId = userIds.split(",");
		
		sql = "delete from T_USER_ROLE where ROLE_ID = '" + roleId + "' and USER_ID = ?";
		AccessDataBaseUtil.deleteByIds(sql, userId);
		return "\"删除成功\"";
	}

	/** 
	 * 描述：listGroup 该角色隶属于的组列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:13:19 PM
	 * @author chun_chang
	 */
	public Object listGroup(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String name = jsonObject.getString("groupName");
		
		sql = " from t_group r left join t_group_role s on r.group_id = s.group_id and s.role_id = ?";
		if (StringUtils.isNotBlank(name)) {
			sql += " and r.caption like '%" + name + "%'";
		}
		String countSql = "select count(*)" + sql;
		String querySql = "select r.group_id, r.caption, s.role_id " + sql + " order by role_id desc";
		String[] fields = { "group_id", "caption", "role_id" };
		Object[] params = { roleId };
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), params);
	}

	/** 
	 * 描述：saveGroup 保存该角色的组列表
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @CreateOn Jul 10, 2012  5:13:31 PM
	 * @author chun_chang
	 */
	public Object saveGroup(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String roleId = jsonObject.getString("roleId");
		String groupIds = jsonObject.getString("groupId");
		String[] groupId = groupIds.split(",");
		
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		
		buff.append("delete from T_GROUP_ROLE where ROLE_ID = '").append(roleId).append("'");
		list.add(buff.toString());
		buff.setLength(0);
		if(!"".equals(groupIds)){
			for (String id1 : groupId) {
				buff.append("insert into T_GROUP_ROLE(G_R_ID,ROLE_ID,GROUP_ID)")
				.append("values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("',")
				.append("'").append(roleId).append("',")
				.append("'").append(id1).append("'")
				.append(")");
				list.add(buff.toString());
				buff.setLength(0);
			}
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

}
